package top.likeqc.moneymark.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.likeqc.moneymark.common.dto.LoginDTO;
import top.likeqc.moneymark.common.lang.Result;
import top.likeqc.moneymark.entity.User;
import top.likeqc.moneymark.service.UserService;
import top.likeqc.moneymark.util.JwtUtils;

import javax.servlet.http.HttpServletResponse;

/**
 * @author likeqc.top
 * @date 2021/7/3 16:08
 */
@RestController
public class LoginController {
    @Autowired JwtUtils jwtUtils;
    @Autowired UserService userService;

    /** 默认账号密码 1：1 */
    /**
     * 登陆
     *
     * @param loginDto 用户名和密码
     * @param response
     * @return
     */
    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDTO loginDto, HttpServletResponse response) {
        User user =
                userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "用户不存在");

        // if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
        if (!user.getPassword().equals(loginDto.getPassword())) {
            return Result.fail("密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        return Result.succ("登陆成功",
                MapUtil.builder()
                        .put("id", user.getId())
                        .put("username", user.getUsername())
                        .put("mobileNumber", user.getMobileNumber())
                        .put("email", user.getEmail())
                        .put("avatar", user.getAvatar())
                        .put("createTime", user.getCreateTime())
                        .map());
    }

    /**
     * 注销
     *
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ("退出登陆");
    }
}
